/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package smoker2;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import smoker.Material;


public class Tisch {
    Set<Material> mats = new HashSet<>();
    Lock lock = new ReentrantLock();
    Condition newMaterial = lock.newCondition();
    Condition tableEmpty = lock.newCondition();
    
    public void put(Set<Material> mat) throws InterruptedException {
        try {
            lock.lock();
            while (mats.size() == 2)
                tableEmpty.await();       

            System.out.println("\t\tAgent legt " + mat +  " auf den Tisch");
            mats = mat;

            newMaterial.signalAll(); 
        } finally {
            lock.unlock();
        }
    }
    
    
    public void take(Material own) throws InterruptedException {
        try {
            lock.lock();
            while (mats.size() == 0 || mats.contains(own)) {
                newMaterial.await();
            }
            System.out.println("Smoker mit " + own + " nimmt "+ mats + ", rollt sich eine Zigarette und raucht diese");

            Thread.currentThread().sleep(500);

            System.out.println("Smoker mit "+ own + " hat fertiggeraucht");
            mats.clear();

            tableEmpty.signal();
        } finally {
            lock.unlock();
        }
    }
            
    
}
